$(document).ready(function() {
	initSize();
	Judgeidentity();
	var layer = layui.layer,
		form = layui.form;

	//获取当前时间
	$("#curtime").showCurrentTime();
	//获取当前日期
	$("#curdate").showCurrentDate();

	$("#week").html("星期" + "日一二三四五六".charAt(new Date().getDay()));
	$("#orgname").html(localStorage.getItem('username'));


	AMap.plugin('AMap.Weather', function() {
		var weather = new AMap.Weather();
		//查询实时天气信息, 查询的城市到行政级别的城市，如朝阳区、杭州市
		weather.getLive('栖霞区', function(err, data) {
			if (!err) {
				//获取温度
				$("#temp").html("当前" + data.temperature + "℃");
				//获取天气
				$("#weather").html("天气：" + data.weather);
			}
		});
	});
	$(document).ajaxError(function (event, xhr, options, exc) {
		console.log(xhr)
	    if (xhr.status == 200) {
	        loginOut()
	    }
	})
	$(document).ajaxSuccess(function(event, xhr, options) {
		console.log(xhr.status)
		if (xhr.responseJSON.status == 401) {
			loginOut()
		}
	})
	$('.main-left-nav-item').click(function() {
		if (this.id != '') {
			window.location.href = this.id + '.html';
		}

	})
	$.each($(".main-left-nav-item"), function(index, el) {
		if (window.location.href.indexOf(el.id) > -1) {
			$('#' + el.id).addClass('active');
		}

	});

	$('#logout').click(function() {
		logout();
	})

	initWebSocket();
	// showImg()
	// showLocalPic('868327076019247')
	
	// layer.open({
	// 	title: '<span style="color:red;font-weight:bold;margin-right: 10px;">警告</span><i style="color: red;" class="fa fa-bullhorn"></i>',
	// 	type: 1,
	// 	offset: 'rb',
	// 	area: '300px',
	// 	skin: 'my_skyn',
	// 	move: false,
	// 	content: `<div style="padding: 20px; color:#fff">
	// 		<span><i style="width:18px;color: green;" class="fa fa-cubes"></i>设备类型：</span>
	// 		<span><i style="width:18px;color: green;" class="fa fa-cubes"></i>设备名称：</span>
	//         <span><i style="width:18px;color: red;" class="fa fa-exclamation-triangle"></i>报警原因：</span>
	//         <i style="width:18px;color: gray;" class="fa fa-clock-o"></i>上报时间：</span>
	//         <i style="width:18px;color: #ed741b;" class="fa fa-user"></i>工地名称：</span>
	// 		<div onclick="showLocalPic()" class="showImgTab">查看截图</div>
	//         </div>
	// 		`,
	// 	shade: 0, //不显示遮罩
	// });
	
})



/*初始化默认字体大小*/
function initSize() {
	//适应不同分辨率
	let fontSize;
	resize();
	window.onresize = resize;

	function resize() {

		let winW = window.innerWidth;
		if (winW >= 1440) {
			fontSize = winW / 1440 * 100
		}
		document.getElementsByTagName('html')[0].style.cssText = "font-size:" + fontSize + "px";
	}


}


///数组排序
function getMaxSort(arr) {
	var max
	for (var i = 0; i < arr.length; i++) {
		for (var j = i; j < arr.length; j++) {
			if (arr[i] < arr[j]) {
				max = arr[j]
				arr[j] = arr[i]
				arr[i] = max
			}
		}
	}
	return arr
}


///图片自动旋转
function rotatepic(id) {
	//图片旋转
	var img = $("#" + id);
	var speed = 30;
	var deg = 0;
	setInterval(function() {
		img.css({
			'-ms-transform': 'rotate(' + deg + 'deg)',
			/* IE 9 */
			'-moz-transform': 'rotate(' + deg + 'deg)',
			/* Firefox */
			'-webkit-transform': 'rotate(' + deg + 'deg)',
			/* Safari and Chrome */
			'-o-transform': 'rotate(' + deg + 'deg)',
			/* Opera */
			'transform': 'rotate(' + deg + 'deg)'
		});
		deg += 1;
		if (deg >= 360) {
			deg = 0;
		}
	}, speed);

}



/*图片循环*/
$.fn.scrollLoop = function(options) {

	var def = $.extend({
		'time': 5000,
		'offsetX': -50,
		'deltaX': 50,
		'offsetY': 0,
		'deltaY': 0,
		'position_type': 'absolute',
		'play_count': -1
	}, options);

	if (def['play_count'] == 0)
		return this;
	else
		def['play_count']--;

	return this.css({
		position: def['position_type'],
		left: def['offsetX'],
		top: def['offsetY']
	}).animate({
		left: def['deltaX'],
		top: def['deltaY']
	}, def['time'], function() {
		$(this).scrollLoop({
			'time': def['time'],
			'offsetX': def['offsetX'],
			'deltaX': def['deltaX'],
			'offsetY': def['offsetY'],
			'deltaY': def['deltaY'],
			'position_type': def['position_type'],
			'play_count': def['play_count']
		});
	});
}


$('#reback').click(function() {
	var roleid = JSON.parse(localStorage.getItem('loginUser')).roleId;
	if (roleid == 1 || roleid == 2 || roleid == 3) {
		window.location.href = "index.html";
	} else {

		window.location.href = "home.html";
	}

})


/*判断字段是否为空或者*/
function checkNullOrEmpty(field) {

	if (field == null || field === "") {
		return ''
	} else {
		return field
	}

}

/**/


/*字符长度过长处理*/
function exceedingLengthHandle(str, length) {
	if (str == null) {
		str = ''
	}
	return (str.length < length) ? str : (str.substring(0, length) + '...')

}




function logout() {
	layer.confirm('确定退出系统？', {
		btn: ['确定', '取消'] //按钮
	}, function() {
		loginOut();
	});
}

function loginOut() {
	$.ajax({
		url: ajaxPrefix() + '/logout',
		type: "post",
		contentType: "application/json",
		success: function(result) {
			localStorage.setItem('isLogin', "");
			localStorage.setItem('sessionId', "");
			localStorage.setItem('username', '');
			window.location.href = "login.html";
		},
		error: function(result) {
			localStorage.setItem('isLogin', "");
			localStorage.setItem('sessionId', "");
			localStorage.setItem('username', '');
			window.location.href = "login.html";
		}
	})
}


function Judgeidentity() {
	var sessionId = localStorage.getItem('sessionId');
	if (sessionId == null || sessionId == "") {
		window.location.href = "login.html";
	}
}


function ajaxPrefix() {
	return '/rest/v1'
}

function Ajax(url, callBack, parms, type) {
	$.ajax({
		url: '/rest/v1' + url,
		type: type ? type : 'get',
		data: parms ? parms : '',
		contentType: "application/json",
		beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
		},
		success: function(result) {
			if (result.status == 200) {
				callBack(result);
			}

		}
	});
}


function AjaxRequest(url, callBack, parms, type) {
	$.ajax({
		url: '/rest/v1' + url,
		type: type ? type : 'get',
		data: parms ? JSON.stringify(parms) : '',
		headers: {
			SessionId: localStorage.getItem('sessionId')
		},
		contentType: "application/json",
		success: function(result) {

			callBack(result);

		}
	});
}


//百度转高德
function bd_toGd(bd_lng, bd_lat) {
	var X_PI = Math.PI * 3000.0 / 180.0;
	var x = bd_lng - 0.0065;
	var y = bd_lat - 0.006;
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
	var gg_lng = z * Math.cos(theta);
	var gg_lat = z * Math.sin(theta);
	return {
		lng: gg_lng,
		lat: gg_lat
	}
}

var GPS = {
	PI: 3.14159265358979324,
	x_pi: 3.14159265358979324 * 3000.0 / 180.0,
	delta: function(lat, lon) {
		// Krasovsky 1940
		//
		// a = 6378245.0, 1/f = 298.3
		// b = a * (1 - f)
		// ee = (a^2 - b^2) / a^2;
		var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
		var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
		var dLat = this.transformLat(lon - 105.0, lat - 35.0);
		var dLon = this.transformLon(lon - 105.0, lat - 35.0);
		var radLat = lat / 180.0 * this.PI;
		var magic = Math.sin(radLat);
		magic = 1 - ee * magic * magic;
		var sqrtMagic = Math.sqrt(magic);
		dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
		dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
		return {
			'lat': dLat,
			'lon': dLon
		};
	},

	//GPS---高德
	gcj_encrypt: function(wgsLat, wgsLon) {
		/*        if (this.outOfChina(wgsLat, wgsLon))
		            return { 'lng': wgsLat, 'lat': wgsLon };*/

		var d = this.delta(wgsLat, wgsLon);
		return {
			'lng': wgsLat + d.lat,
			'lat': wgsLon + d.lon
		};
	},
	outOfChina: function(lat, lon) {
		if (lon < 72.004 || lon > 137.8347)
			return true;
		if (lat < 0.8293 || lat > 55.8271)
			return true;
		return false;
	},
	transformLat: function(x, y) {
		var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
		ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
		ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
		return ret;
	},
	transformLon: function(x, y) {
		var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
		ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
		ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
		return ret;
	}
};

function getAppName(appid) {
	var projectname;
	if (appid == 1) {
		projectname = '消火栓';
	} else if (appid == 2) {
		projectname = '喷淋末端';
	} else if (appid == 5) {
		projectname = '消防水池水箱';
	} else if (appid == 6) {
		projectname = '烟雾报警器';
	} else if (appid == 7) {
		projectname = '消防泵';
	} else if (appid == 9) {
		projectname = '门磁设备';
	} else if (appid == 16) {
		projectname = '电气火灾设备';
	} else if (appid == 18) {
		projectname = '电气火灾监测';
	} else if (appid == 19) {
		projectname = '火灾自动报警';
	} else if (appid == 20) {
		projectname = '消防风机';
	} else if (appid == 21) {
		projectname = '消防泵信息';
	} else if (appid == 22) {
		projectname = '消防用水量';
	} else if (appid == 23) {
		projectname = '可燃气体监测';
	} else if (appid == 26) {
		projectname = '地磁车位监测';
	} else if (appid == 27) {
		projectname = '浸水监测';
	} else if (appid == 28) {
		projectname = '火眼监测';
	} else if (appid == 29) {
		projectname = '充电桩监测';
	} else if (appid == 30) {
		projectname = '温湿度监测';
	} else if (appid == 31) {
		projectname = '阀门监测';
	} else if (appid == 32) {
		projectname = '棣拓单相电气监测';
	} else if (appid == 33) {
		projectname = '配电箱温度监测';
	} else if (appid == 34) {
		projectname = '工况监测';
	} else if (appid == 35) {
		projectname = '手动报警监测';
	};
	return projectname;
}
///websorket实时报警
var curFlag = 0;//判断弹窗数量
function initWebSocket() {
	console.log('WebSocket')
	console.log(JSON.parse(localStorage.getItem('isLogin')).sessionId)
	if (!window.WebSocket) {
		return false;
	}

	var id = '';
	// var sessionId = '';
	if (!localStorage.getItem('isLogin')) {
		id = '';
		// sessionId = '';
	} else {
		id = JSON.parse(localStorage.getItem('isLogin')).userId;
		// sessionId = JSON.parse(localStorage.getItem('isLogin')).sessionId;
	}

	if (id == null || id == "") {
		return false;
	}
	console.log(id)
	// console.log(sessionId)
	//webSocket = new WebSocket("ws://192.168.0.148:8088/rest/websocket/" + userId);
	// webSocket = new WebSocket("ws://websocket.njdtwise.com:8088/websocket/" + userId);
	webSocket = new WebSocket("ws://dev.njdtwise.com:9083/websocket/" + id);
	// http://dev.njdtwise.com

	webSocket.onopen = function(evt) {
		tryTime = 0;
	};
	webSocket.onmessage = function(msg) {
		console.log(msg)
		msg = eval("(" + msg.data + ")");
		if (msg.data == "&") {

		} else {
			curFlag++;
			fireEyesCurrentStatus(1);
			layer.open({
				title: '<span style="color:red;font-weight:bold;margin-right: 10px;">警告</span><i style="color: red;" class="fa fa-bullhorn"></i>',
				type: 1,
				offset: 'rb',
				skin: 'my_skyn',
				area: '300px',
				move: false,
				content: `<div style="padding: 20px;color:#fff">
					<span><i style="width:18px;color: green;" class="fa fa-cubes"></i>设备类型：</span>
					<span>` + msg.deviceTypeDesc + `</span></br>
					<span><i style="width:18px;color: green;" class="fa fa-cubes"></i>设备名称：</span>
					<span>` + msg.deviceName + `</span></br>
                    <span><i style="width:18px;color: red;" class="fa fa-exclamation-triangle"></i>报警原因：</span>
                    <span>` + msg.eventDesc + `</span></br>
                    <i style="width:18px;color: gray;" class="fa fa-clock-o"></i>上报时间：</span>
                    <span>` + msg.dataTime + `</span></br>
                    <i style="width:18px;color: #ed741b;" class="fa fa-user"></i>工地名称：</span>
                    <span>` + (msg.projectName == undefined ? '暂无' : msg.projectName) + `</span></br>
					<div onclick="showLocalPic(`+ msg.deviceCode + `,` + msg.deviceType +`)" class="showImgTab">查看截图</div>
                    </div>
					`+(curFlag>1?'':'<audio autoplay="autoplay" loop><source src="../static/video/fire.ogg" type="audio/ogg"><source src="../static/video/fire.mp3" type="audio/mpeg"></audio>'),
				shade: 0, //不显示遮罩
			});
		}
	};

	webSocket.onerror = function(evt) {};

	webSocket.onclose = function() {
		// 重试2次，每次之间间隔2秒
		if (tryTime < 4) {
			setTimeout(function() {
				webSocket = null;
				tryTime++;
				initWebSocket();
			}, 5 * 1000);
		} else {}
	};
}

function closeWebSocket() {
	if (webSocket) {
		webSocket.close();
	}
}


// 
// 视频画面查看现场截图
showLocalPic = (code, deviceType) => {

	//自定页
	layer.open({
		title: "视频联动报警画面",
		type: 1,
		closeBtn: 0, //不显示关闭按钮
		anim: 2,
		skin: 'my_skyn',
		shadeClose: true, //开启遮罩关闭
		area: ['7rem', '5rem'],
		content: '<div id="websocket-img" style="display:flex;justify-content: space-around;align-items: center;flex-wrap: wrap;;height: 100%;color:#fff">点击刷新加载照片...</div>',
		btn: ['刷新', '关闭'],
		yes: function(index, layero) {
			reFlashPic(code,deviceType)

		},
		success: function(layero, index) {
			reFlashPic(code,deviceType)
		}
	});

}

// 刷新推送报警图片
reFlashPic = (code,deviceType) => {

	// if (appid == 19&&(deviceId.indexOf('-')>-1)) {
	//     var url = '/file/biz/lastest?appid=19&id=' + deviceId.split('-')[1] + '&num=4'
	// } else {
	// }
	// var url = '/rest/v1/manage/device/screenshot/list?appid=' + appid + '&id=' + euid + '&num=4'
	var currentDate = getCurrentDateOnly();
	var url = "/manage/device/screenshot/list?pageNum=1&pageSize=4&type="+deviceType+"&code=" + code + "&beginDate="+currentDate+"&endDate="+currentDate

	Ajax(url, checkPicCallback)

	// AjaxRequest(url, checkPicCallback);

	function checkPicCallback(result) {
		var data = result.result.data;
		$("#websocket-img").empty().append(data.reduce((x, y) => {
			return x + `<div style="width: 40%;height: 1.8rem; color:#fff" onclick="scalePic('${y.dataTime}','${y.filePath}')">
							<img src="${'/images/' + y.filePath}" style="width: 100%;height: 1.4rem;">
							<div style="width: 100%;">上报设备：${y.deviceName}</div>
							<div style="width: 100%;">上报时间：${y.dataTime}</div>
							<div style="width: 100%;">工地名称：${y.projectName}</div>
						</div>`
		}, ''))

	}
}
// 图片放大
scalePic = (time, filePath) => {
	var pD = []

	pD.push({
		"alt": "图片名",
		"pid": time, //图片id
		"src": "/images/" + filePath, //原图地址
		"thumb": "/images/" + filePath //缩略图地址
	})

	layer.photos({
		photos: {
			"title": "", //相册标题
			"id": 123, //相册id
			"start": 0, //初始显示的图片序号，默认0
			"data": pD
		},
		anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
	});
}

//获取当前日期
function getCurrentDateOnly() {  
    const now = new Date();  
    const year = now.getFullYear();  
    const month = String(now.getMonth() + 1).padStart(2, '0'); // getMonth() 是从0开始的，所以需要加1  
    const day = String(now.getDate()).padStart(2, '0');  
  
    return `${year}-${month}-${day}`;  
}

function getDaysBefore(daysBack) {
 // 创建一个新的Date对象，表示当前日期和时间  
    let today = new Date();  
  
    // 从当前日期中减去指定的天数  
    today.setDate(today.getDate() - daysBack);  
  
    // 使用getFullYear, getMonth (注意月份是从0开始的，所以要+1), 和getDate来获取年、月和日  
    let year = today.getFullYear();  
    let month = String(today.getMonth() + 1).padStart(2, '0'); // 使用padStart来确保月份是两位数  
    let day = String(today.getDate()).padStart(2, '0'); // 使用padStart来确保日期是两位数  
  
    // 将年、月和日组合成所需的格式  
    return `${year}-${month}-${day}`;  
}